from machine import FPIOA
from machine import Pin
from machine import PWM
from machine import UART
import time


deviceLED = FPIOA()
deviceBeep = FPIOA()
deviceUART = FPIOA()


deviceLED.set_function(62, FPIOA.GPIO62)
deviceLED.set_function(20, FPIOA.GPIO20)
deviceLED.set_function(63, FPIOA.GPIO63)
deviceBeep.set_function(43, FPIOA.PWM1)
deviceUART.set_function(11, FPIOA.UART2_TXD)
deviceUART.set_function(12, FPIOA.UART2_RXD)

ledR = Pin(62, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
ledG = Pin(20, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
ledB = Pin(63, Pin.OUT, pull=Pin.PULL_NONE, drive=7)

beep = PWM(1, 4000, duty=50, enable = False)

uart = UART(UART.UART2, baudrate=115200, bits=UART.EIGHTBITS, parity=UART.PARITY_NONE, stop=UART.STOPBITS_ONE);


notes = {
        'C4':261,
        'D4':293,
        'E4':329,
        'F4':349,
        'G4':392,
        'A4':440,
        'B4':493,
        'C5':523,
}



melody = [
    ('C4', 500),('C4', 500),('G4', 500),('G4', 500),
    ('A4', 500),('A4', 500),('G4', 1000),
    ('F4', 500),('F4', 500),('E4', 500),('E4', 500),
    ('D4', 500),('D4', 500),('C4', 1000),
]


songLib = {
    'xxx':melody,
}


def setLEDColor(R, G, B):
    if R == 1:
        ledR.low()
    else:
        ledR.high()
    if G == 1:
        ledG.low()
    else:
        ledG.high()
    if B == 1:
        ledB.low()
    else:
        ledB.high()


def playTone(note, duration):
    frequency = notes.get(note, 0)
    if frequency > 0:
        beep.freq(frequency)
        beep.enable(True)
        time.sleep_ms(duration)
        beep.enable(False)
        time.sleep_ms(50)



def playMusic(music):
    for note, duration in music:
        playTone(note, duration)


uart.write("please input command: LED or Play\r\n\r\n\r\n\r\n")
uart.write("input help for help\r\n")

ledR.high()
ledG.high()
ledB.high()


while True:
    data = uart.read()
    if data != None:
        strData = data.decode()         #转换为字符串

        if -1 != strData.find('led', 0, len(strData)):
            setLEDColor(int(strData[4]), int(strData[6]), int(strData[8]))

        elif -1 != strData.find('play', 0, len(strData)):
            playMusic(melody)

        else:
            print('error\n')
        '''
        if 'led' in data:
            setLEDColor(data[4], data[6], data[8])
        elif 'play' in data:
            print(data[5:8])
            songName = songLib.get(data[5:8],0)
            playMusic(songName)
        '''
    time.sleep_ms(100)
'''
    if data == '0x01':
        print("led\n")
    elif data[0] > 1:
        print("play")
    time.sleep_ms(100)
'''

uart.deinit()
beep.deinit()
